'use strict';
var inherit = require('./utils').inherit;
var Facade = require('./facade');
var Track = require('./track');
var isEmail = require('is-email');
/**
* Initialize new `Page` facade with `dictionary`.
*
* @param {Object} dictionary
* @param {string} category
* @param {string} name
* @param {Object} traits
* @param {Object} options
* @param {Object} opts
* @property {Boolean|Undefined} clone
*/
function Page(dictionary, opts) {
Facade.call(this, dictionary, opts);
}
/**
* Inherit from `Facade`
*/
inherit(Page, Facade);
/**
* Get the facade's action.
*
* @return {string}
*/
Page.prototype.action = function() {
return 'page';
};
Page.prototype.type = Page.prototype.action;
/**
* Fields
*/
Page.prototype.category = Facade.field('category');
Page.prototype.name = Facade.field('name');
/**
* Proxies.
*/
Page.prototype.title = Facade.proxy('properties.title');
Page.prototype.path = Facade.proxy('properties.path');
Page.prototype.url = Facade.proxy('properties.url');
/**
* Referrer.
*/
Page.prototype.referrer = function() {
return this.proxy('context.referrer.url')
|| this.proxy('context.page.referrer')
|| this.proxy('properties.referrer');
};
/**
* Get the page properties mixing `category` and `name`.
*
* @param {Object} aliases
* @return {Object}
*/
Page.prototype.properties = function(aliases) {
var props = this.field('properties') || {};
var category = this.category();
var name = this.name();
aliases = aliases || {};
if (category) props.category = category;
if (name) props.name = name;
for (var alias in aliases) {
var value = this[alias] == null
? this.proxy('properties.' + alias)
: this[alias]();
Iif (value == null) continue;
props[aliases[alias]] = value;
Eif (alias !== aliases[alias]) delete props[alias];
}
return props;
};
/**
* Get the user's email, falling back to their user ID if it's a valid email.
*
* @return {string}
*/
Page.prototype.email = function() {
var email = this.proxy('context.traits.email') || this.proxy('properties.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the page fullName.
*
* @return {string}
*/
Page.prototype.fullName = function() {
var category = this.category();
var name = this.name();
return name && category
? category + ' ' + name
: name;
};
/**
* Get event with `name`.
*
* @return {string}
*/
Page.prototype.event = function(name) {
return name
? 'Viewed ' + name + ' Page'
: 'Loaded a Page';
};
/**
* Convert this Page to a Track facade with `name`.
*
* @param {string} name
* @return {Track}
*/
Page.prototype.track = function(name) {
var json = this.json();
json.event = this.event(name);
json.timestamp = this.timestamp();
json.properties = this.properties();
return new Track(json, this.opts);
};
/**
* Exports.
*/
module.exports = Page;
|